package com.landinfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.esri.core.geometry.GeometryEngine;
import com.landinfo.service.ShapefileService;
import com.vividsolutions.jts.geom.Geometry;
import org.geotools.data.*;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ziqilv on 2017/4/2.
 * Shapefile文件操作类
 */
@Service
@Transactional
public class ShapefileServiceImpl implements ShapefileService {
  /**
   * 打开Shp文件并返回Feature
   *
   * @param shpFileName
   * @return
   */
  @Override
  public String openShpFile(String shpFileName) throws IOException {
    File file = new File(shpFileName);
    if (file == null || !file.exists()) {
      return "";
    }

    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource featureSource = store.getFeatureSource();
    FeatureCollection<SimpleFeatureType, SimpleFeature> collection = featureSource.getFeatures();
    FeatureIterator<SimpleFeature> features = collection.features();
    List<String> resultFeatures = new ArrayList<>();
    while (features.hasNext()) {
      SimpleFeature feature = features.next();
      // 将wkt类型Geometry转成geojson
      Geometry geom = (Geometry) feature.getDefaultGeometry();
      com.esri.core.geometry.Geometry geometry = GeometryEngine.geometryFromWkt(geom.toText(), 0, com.esri.core.geometry.Geometry.Type.Unknown);
      resultFeatures.add(GeometryEngine.geometryToJson(4326, geometry));
    }
    Map<String, Object> map = new HashMap<>();
    map.put("geometries", resultFeatures);
    return JSON.toJSONString(map);
  }

  public void createFeature() {
//    // 创建图层，创建一个多边形图层，这里没有指定空间参考，如果需要的话，需要在这里进行指定
//    Layer oLayer = dataSource.CreateLayer("TestPolygon", null, ogr.wkbPolygon, null);
//    if (oLayer == null) {
//      System.out.println("图层创建失败！\n");
//      return;
//    }
//
//    // 下面创建属性表
//    // 先创建一个叫FieldID的整型属性
//    FieldDefn oFieldID = new FieldDefn("FieldID", ogr.OFTInteger);
//    oLayer.CreateField(oFieldID, 1);
//
//    // 再创建一个叫FeatureName的字符型属性，字符长度为50
//    FieldDefn oFieldName = new FieldDefn("FieldName", ogr.OFTString);
//    oFieldName.SetWidth(100);
//    oLayer.CreateField(oFieldName, 1);
//
//    FeatureDefn oDefn = oLayer.GetLayerDefn();
//
//    // 创建三角形要素
//    Feature oFeatureTriangle = new Feature(oDefn);
//    oFeatureTriangle.SetField(0, 0);
//    oFeatureTriangle.SetField(1, "三角形");
//    Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON ((0 0,20 0,10 15,0 0))");
//    oFeatureTriangle.SetGeometry(geomTriangle);
//
//    oLayer.CreateFeature(oFeatureTriangle);
//
//    // 创建矩形要素
//    Feature oFeatureRectangle = new Feature(oDefn);
//    oFeatureRectangle.SetField(0, 1);
//    oFeatureRectangle.SetField(1, "矩形");
//    Geometry geomRectangle = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))");
//    oFeatureRectangle.SetGeometry(geomRectangle);
//
//    oLayer.CreateFeature(oFeatureRectangle);
//
//    // 创建五角形要素
//    Feature oFeaturePentagon = new Feature(oDefn);
//    oFeaturePentagon.SetField(0, 2);
//    oFeaturePentagon.SetField(1, "五角形");
//    Geometry geomPentagon = Geometry.CreateFromWkt("POLYGON ((70 0,85 0,90 15,80 30,65 15,70 0))");
//    oFeaturePentagon.SetGeometry(geomPentagon);
//
//    oLayer.CreateFeature(oFeaturePentagon);
//
//    //写入文件
//    oLayer.SyncToDisk();
//    dataSource.SyncToDisk();
//
//    System.out.println("\n数据集创建完成！\n");
  }

  /**
   * 转成uft-8编码
   *
   * @param string
   * @return
   */
  public static String getUTF8XMLString(String string) {
    // A StringBuffer Object
    StringBuffer sb = new StringBuffer();
    sb.append(string);
    String xmString = "";
    String xmlUTF8 = "";
    try {
      xmString = new String(sb.toString().getBytes("UTF-8"));
      xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
      System.out.println("utf-8 编码：" + xmlUTF8);
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return xmlUTF8;
  }
}
